﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Caching;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Jugg.Core.Caching
{
    public class MemoryCacheManager : ICacheManager
    {
        /// <summary>
        /// 
        /// </summary>
        protected ObjectCache Cache
        {
            get
            {
                return MemoryCache.Default;
            }
        }

        public void clear()
        {
            foreach (var item in Cache)
                remove(item.Key);
        }

        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public T get<T>(string key)
        {
            return (T)Cache[key];
        }

        /// <summary>
        /// 检测是否存在
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool isSet(string key)
        {
            return (Cache.Contains(key));
        }

        /// <summary>
        /// 移除
        /// </summary>
        /// <param name="key"></param>
        public void remove(string key)
        {
            Cache.Remove(key);
        }

        public void removeByPattern(string pattern)
        {
            var regex = new Regex(pattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase);
            var keysToRemove = new List<String>();

            foreach (var item in Cache)
                if (regex.IsMatch(item.Key))
                    keysToRemove.Add(item.Key);

            foreach (string key in keysToRemove)
            {
                remove(key);
            }
        }

        /// <summary>
        /// 缓存
        /// </summary>
        /// <param name="key"></param>
        /// <param name="data"></param>
        /// <param name="cacheTime"></param>
        public void set(string key, object data, int cacheTime)
        {
            if (data == null)
                return;
            var policy = new CacheItemPolicy();
            policy.AbsoluteExpiration = DateTime.Now + TimeSpan.FromMinutes(cacheTime);
            Cache.Set(new CacheItem(key, data), policy);
        }
    }
}
